/*
 *接口编写处...
*如果接口需要做Action的权限验证，请在Action上使用属性
*如: [ApiActionPermission("cw_djlc_djzb",Enums.ActionPermissionOptions.Search)]
 */
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using VOL.Entity.DomainModels;
using VOL.Finance.IServices;
using Newtonsoft.Json;
using VOL.Core.Extensions;
using VOL.Core.Float;
using VOL.Core.ManageUser;
using VOL.Core.Utilities;
using VOL.Core.DBManager;
using System.Linq;
using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
using VOL.Core.Filters;
using System.Data;
using VOL.WebApi.Controllers.MyTable.TaskList;
using Autofac.Core;
using static Dapper.SqlMapper;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Text;
using System.Net;
using System.Diagnostics;
using System.Security.Permissions;
using VOL.Core.Middleware;
using StackExchange.Redis;

namespace VOL.Finance.Controllers
{
    public partial class cw_djlc_djzbController
    {
        private readonly Icw_djlc_djzbService _service;//访问业务代码
        private readonly IHttpContextAccessor _httpContextAccessor;

        [ActivatorUtilitiesConstructor]
        public cw_djlc_djzbController(
            Icw_djlc_djzbService service,
            IHttpContextAccessor httpContextAccessor
        )
        : base(service)
        {
            _service = service;
            _httpContextAccessor = httpContextAccessor;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="cw_djlc_djzb_id"></param>
        /// <param name="synchronizationstatus"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        [HttpPost, Route("updateSynchronizationStatus")]//,AllowAnonymous
        [ApiActionPermission()]
        public WebResponseContent updateSynchronizationStatus( string cw_djlc_djzb_id, string type)
        {
            WebResponseContent webResponse = new WebResponseContent();
            var dapper = DBServerProvider.SqlDapper;
            string updateStatus = null;
            
            try
            {
                dapper.BeginTrans();
                if (type == "synchronizationbom")
                {
                    updateStatus = "update cw_djlc_djzb set synchronizationbomstatus = 1 " +
                            "where cw_djlc_djzb_id = @value";
                }
                if (type == "synchronizationprice")
                {
                     updateStatus = "update cw_djlc_djzb set synchronizationpricestatus = 1 " +
                            "where cw_djlc_djzb_id = @value";
                }
                var data2 = dapper.ExcuteNonQuery(updateStatus, new { value = cw_djlc_djzb_id });
                dapper.Commit();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                dapper.Rollback();
            }
            return webResponse.OK("操作成功！");
        }
        [ApiActionPermission()]
        [HttpPost, Route("checkHuiqianUser")]//,AllowAnonymous
        public ActionResult checkHuiqianUser(string hq_tousername)
        {
            WebResponseContent webResponse = new WebResponseContent();
            if (!string.IsNullOrEmpty(hq_tousername))
            {
                string[] hq_tousername_array = hq_tousername.Split(',');//汇签人员名单
                if (hq_tousername_array.Contains(UserContext.Current.UserName))
                {
                    webResponse.Code = "-1";
                    webResponse.Message = "汇签人不能是自己，请重新选择！";
                    return Json(webResponse);
                }
            }
            return Json(webResponse.OK());
        }
        /// <summary>
        /// 提交审核,后续再改成通用提交
        /// </summary>
        /// <param name="reimids"></param>
        /// <param name="pdata"></param>
        /// <param name="hq_tousername">汇签的人</param>
        /// <returns></returns>
        [ActionLog]
        [ApiActionPermission()]
        [HttpPost, Route("Audit_tj")]//,AllowAnonymous
        public  WebResponseContent Audit_tj(string reimids, string pdata, string hq_tousername)
        {
            WebResponseContent webResponse = new WebResponseContent();
            WebResponseContent webResponseIsSuccess = new WebResponseContent();
            string[] ls_id = reimids.Split(',');
            string[] hq_tousername_array = null;
            if (!string.IsNullOrEmpty(hq_tousername))
                hq_tousername_array = hq_tousername.Split(',');//汇签人员名单
            List<Guid> ls_list = new List<Guid>();
            foreach (var item in ls_id)
            {
                ls_list.Add((Guid)item.ToGuid());
            }
            List<cw_djlc_djzb> cw_djlc_djzb_list = DBServerProvider.DbContext.Set<cw_djlc_djzb>().Where(s => ls_list.Contains(s.cw_djlc_djzb_id)).ToList();            
            dynamic queryJson = JsonConvert.DeserializeObject(pdata);//接受前端提交的表单（意见）
            var user = UserContext.Current.GetUserInfo(UserContext.Current.UserId);
            foreach (cw_djlc_djzb item in cw_djlc_djzb_list)
            {
                if (!string.IsNullOrEmpty(hq_tousername) && hq_tousername_array.Length > 0)
                {
                    for (int i = 0; i < hq_tousername_array.Length; i++)
                    {
                        FloatManager.add_task(item, (int)item.stepid, hq_tousername_array[i], "汇签");
                    }

                }
                if (queryJson.reyijian.ToString() == "回退")//回退到指定步骤
                {
                    float_white_list_user float_white_list_user = DBServerProvider.DbContext.Set<float_white_list_user>().Where(x => x.ft_table == "cw_djlc_djzb" && x.step_id == 40 && x.user_id == UserContext.Current.UserId).FirstOrDefault();
                    if (!float_white_list_user.IsNullOrEmpty())
                    {
                        return webResponseIsSuccess.Error("该用户未拥有回退操作权限");
                    }
                    //int pre_stepid = FloatManager.get_pre_step((int)item.stepid, item.cw_djlc_djzb_id);
                    int to_stepid = int.Parse(queryJson.to_stepid.ToString());
                    List<fk_reimtask> fk_reimtaskList = DBServerProvider.DbContext.Set<fk_reimtask>().Where(s => ls_list.Contains((Guid)s.reimid) && s.stepid == to_stepid).ToList();
                    if (fk_reimtaskList.Count == 0)
                    {
                        return webResponseIsSuccess.Error("回退到的角色有误，流程暂未流转到该角色审批");
                    }
                    FloatManager.Audit_To_Stepid(item, queryJson.remark.ToString(), to_stepid);
                }
                else if (queryJson.reyijian.ToString() == "不同意")//回退到起始步骤
                {
                    float_white_list_user float_white_list_user = DBServerProvider.DbContext.Set<float_white_list_user>().Where(x => x.ft_table == "cw_djlc_djzb" && x.step_id == 40 && x.user_id == UserContext.Current.UserId).FirstOrDefault();
                    if (!float_white_list_user.IsNullOrEmpty())
                    {
                        return webResponseIsSuccess.Error("该用户未拥有不同意操作权限");
                    }
                    //FloatManager.Audit_To_Stepid(item, queryJson.remark.ToString(), FloatManager.GetFirstStepid(item));
                    FloatManager.Audit(item, queryJson.reyijian.ToString(), queryJson.remark.ToString());
                }
                else
                {
                    /// 判断该条流程是否已去SAP同步，并未同步到数据
                    if (item.synchronizationbomstatus == 1 && item.synchronizationpricestatus == 1 && item.is_synchronized_bom == 0)
                    {
                        return webResponseIsSuccess.Error("需求车型物料号未从SAP同步到数据，请确认车型物料号是否正确");
                    }
                    FloatManager.Audit(item, queryJson.reyijian.ToString(), queryJson.remark.ToString());//正常审核提交
                    /// 如果是流程第一次进行审核提交的时候，需要自动进行同步BOM、同步价格
                    /// 这里直接调用同步BOM、价格的定时任务即可
                    /*if (item.stepid == 20)
                    {
                        Task.Run(() => new backTaskController().test_task_api());
                    }*/
                }
            };
             return webResponse.OK("操作成功！");
        }

        [ApiActionPermission()]
        public override IActionResult Upload(IEnumerable<IFormFile> fileInput)
        {
            return base.Upload(fileInput);
        }
        [ApiActionPermission()]
        [HttpPost, Route("browseGetPageData")]//,AllowAnonymous
        public ActionResult browseGetPageData([FromBody] PageDataOptions loadData)
        {
            return Json(_service.browseGetPageData(loadData));
        }

        [ApiActionPermission()]
        [HttpPost,Route("getUserInfo")]
        public ActionResult getUserInfo()
        {
            UserInfo user = UserContext.Current.GetUserInfo(UserContext.Current.UserId);
            return Json(user);
        }
        /// <summary>
        /// 废弃功能
        /// </summary>
        /// <param name="cw_djlc_djzb_id"></param>
        /// <returns></returns>
        [ApiActionPermission]
        [HttpPost,Route("updateIsEnable")]
        public ActionResult updateIsEnable(string cw_djlc_djzb_id)
        {
            WebResponseContent webResponse = new WebResponseContent();
            if (string.IsNullOrEmpty(cw_djlc_djzb_id))
            {
                return Json(webResponse.Error("数据不能为空,请检查！"));
            }
            cw_djlc_djzb cw_djlc_djzb = DBServerProvider.DbContext.Set<cw_djlc_djzb>().Where(x => x.cw_djlc_djzb_id == Guid.Parse(cw_djlc_djzb_id)).ToList().FirstOrDefault();
            if (!cw_djlc_djzb.IsNullOrEmpty())
            {
                cw_djlc_djzb.is_enable = 0;//0废弃 1启用
                DBServerProvider.DbContext.Update(cw_djlc_djzb);
                DBServerProvider.DbContext.SaveChanges();
            }
            return Json(webResponse.OK("操作成功！"));                           
        }

        [ApiActionPermission()]
        public override ActionResult Update([FromBody] SaveModel saveModel)
        {
            return base.Update(saveModel);
        }
    }
}
